<template>
  <VolBox :lazy="true" :model.sync="model" :title="title" :height="550" :width="1000">
    <VolForm ref="myform" :label-width="100" :loadKey="true" :formFields="formFields1" :formRules="formRules1"></VolForm>
    <el-form ref="editFormFields" :rules="rules" :model="editFormFields" :inline="true" label-width="100px">
      <el-form-item label="券模板名称" prop="name">
        <el-input v-model.trim="editFormFields.name" placeholder="请输入券模板名称"></el-input>
      </el-form-item>
      <el-form-item label="券类型" prop="type">
        <el-select v-model="editFormFields.type" placeholder="请输入券类型">
          <el-option v-for="(i, ii) in typeList" :key="ii" :label="i.label" :value="i.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="券模板编码" prop="discountCode">
        <el-input v-model.trim="editFormFields.discountCode" placeholder="请输入券模板编码"></el-input>
      </el-form-item>
      <el-form-item label="券模板描述" prop="discountRefer">
        <el-input v-model.trim="editFormFields.discountRefer" placeholder="请输入券模板描述"></el-input>
      </el-form-item>
      <el-form-item v-show="coupValuStatus" label="面额" prop="coupon_value">
        <el-input class="meInt" v-model="editFormFields.coupon_value" placeholder="请输入面额">
        </el-input>
        <div class="fr">
          <span v-if="couponStatus">元</span>
          <span v-else>折</span>
        </div>
      </el-form-item>
      <el-form-item class="sysm" label="使用说明" prop="note">
        <el-input :autosize="{ minRows: 4 }" v-model="editFormFields.note" type="textarea"
          placeholder="请输入使用说明"></el-input>
      </el-form-item>
      <div class="hx">财务规则</div>
      <el-form-item label="是否入账" prop="is_entry_accoun">
        <el-switch v-model="editFormFields.is_entry_accoun" active-value="1" inactive-value="0">
        </el-switch>
      </el-form-item>
      <div class="hx"><span style="margin-right:30px;">使用规则</span> </div>
      <el-form-item label="使用门槛" prop="use_threshold">
        <el-radio v-model="editFormFields.use_threshold" label="0">无门槛</el-radio>
        <el-radio v-model="editFormFields.use_threshold" label="1">有门槛</el-radio>
        <div v-show="thresholdValue">
          满
          <el-input size="mini" class="z" v-model="editFormFields.threshold_value" />元可用
        </div>
      </el-form-item>
      <el-form-item label="是否互斥" prop="coupon_mutex">
        <el-switch v-model="editFormFields.coupon_mutex" active-value="1" inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="优惠方案" prop="discount_id">
        <el-select v-model="editFormFields.discount_id" placeholder="请输入优惠方案">
          <el-option v-for="(i, ii) in discount_List" :key="ii" :label="i.label" :value="i.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="sysm" label="规则说明" prop="regulation">
        <el-input :autosize="{ minRows: 4 }" v-model="editFormFields.regulation" type="textarea"
          placeholder="请输入规则说明"></el-input>
      </el-form-item>
      <div class="hx">适用范围</div>
      <div>
        <el-radio-group v-model="editFormFields.applicability" prop="applicability">
          <el-radio label="1" :disabled="applicabilityDisabled">通用</el-radio>
          <el-radio label="2" :disabled="applicabilityDisabled">指定品类</el-radio>
          <el-radio label="3">指定商品</el-radio>
          <el-radio label="4" :disabled="applicabilityDisabled">指定供应商
          </el-radio>
        </el-radio-group>
        <!-- 指定品类 -->
        <div class="cascader" v-if="editFormFields.applicability == 2">
          <el-cascader ref="cascder" v-model="transferValue" :options="PLProtyLIST" clearable :props="{
            multiple: true,
            checkStrictly: true,
            label: 'typeName',
            value: 'id'
          }"></el-cascader>
        </div>
        <!-- 指定商品 -->
        <div class="cascader" v-else-if="editFormFields.applicability == 3">
          <div class="casd">
            <el-cascader ref="cascder" v-model="cascaderValue" :options="PLProtyLIST" clearable :props="{
              checkStrictly: true,
              label: 'typeName',
              value: 'id'
            }" @change="changeCasc"></el-cascader>
          </div>
          <el-select v-if="applicabilityDisabled == true" v-model="selectValue" placeholder="请选择">
            <el-option v-for="item in productsList" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
          <el-transfer v-else v-model="selectValue" :data="productsList" :titles="titles"
            :right-default-checked="selectValue" :render-content="renderFunc"></el-transfer>
        </div>
        <!-- 指定商户 -->
        <!-- <el-transfer v-else-if="editFormFields.applicability == 4"
                     v-model="MerchantValue"
                     :data="MerchantLIST"
                     :titles="titles4"
                     :right-default-checked="MerchantValue"></el-transfer> -->
        <tree-transfer v-else-if="editFormFields.applicability == 4" ref="insideChooseProject" :data="treeTransferData"
          :defaultProps="defaultProps" :checkedList="MerchantValue">
        </tree-transfer>
      </div>
      <div class="hx">领取规则</div>
      <el-form-item label="是否领取" prop="receive_way">
        <el-switch v-model="editFormFields.receive_way" active-value="1" inactive-value="0">
        </el-switch>
      </el-form-item>
      <div v-show="receiveWay">
        <el-form-item label="适用人群" prop="applicable_people">
          <el-radio-group v-model="editFormFields.applicable_people" prop="applicable_people">
            <el-radio label="1">全部</el-radio>
            <el-radio label="2">特定人群</el-radio>
            <el-radio label="3">指定人群</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 特定人群 -->
        <el-form-item v-show="rqStatus">
          消费未满
          <el-input size="mini" class="z" v-model="editFormFields.amount_condition" />元可领
        </el-form-item>
        <!-- 指定人群 -->
        <div class="cascader" v-show="zdPeo">
          <el-transfer v-model="memberType" :data="hylxList" :titles="titles3"
            :right-default-checked="memberType"></el-transfer>
        </div>
        <el-form-item label="领取时间">
          <el-date-picker v-model="editFormFields.receiveTime" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取限制">
          <span>每人每天可领取</span>
          <el-input class="z" size="mini" v-model="editFormFields.per_daylimit"></el-input>
          <span>张，每人总计可领取</span>
          <el-input class="z" size="mini" v-model="editFormFields.per_limit"></el-input>
          <span>张</span>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer">
      <Button type="default" @click="submit('editFormFields')">确认</Button>
      <Button type="default" @click="model = false">关闭</Button>
    </div>
  </VolBox>
</template>

<script>
import VolBox from "@/components/basic/VolBox.vue";
import VolForm from "@/components/basic/VolForm.vue";
import TreeTransfer from "./treeTransfer.vue";
export default {
  components: { VolBox, VolForm, TreeTransfer },
  data() {
    const discountCodeFun = (rule, value, callback) => {
      let regPos = /^[a-zA-Z0-9]+$/
      if (value) {
        if (!regPos.test(value)) {
          return callback(new Error('请输入字母加数字'))
        } else {
          callback()
        }
      } else {
        return callback(new Error('请输入券模板编码'))
      }
    }
    return {
      defaultProps: {
        id: "id",
        children: "children",
        label: "label"
        // pCode:"projectCode"
      },
      //穿梭框选中数据
      treeChecked: [],
      // 穿梭框数据
      treeTransferData: [],
      model: false,
      title: "",
      formFields1: { coupon_cover: "" },
      formRules1: [
        [
          {
            field: "coupon_cover",
            title: "券面图",
            type: "img",
            maxSize: 1,
            url: "/api/MebCoupon/Upload"
          }
        ]
      ],
      editFormFields: {
        discountCode: '',
        discountRefer: '',
        is_entry_accoun: "1",
        creator: "",
        createDate: "",
        name: "",
        type: "",
        note: "",
        coupon_value: 0,
        count: "",
        use_threshold: "0",
        coupon_mutex: "",
        regulation: "",
        applicability: 1,
        receive_way: "",
        applicable_people: "",
        receiveTime: "",
        useTime: "",
        per_daylimit: "",
        per_limit: "",
        member_type: "",
        member_level: "",
        threshold_value: "",
        amount_condition: 0,
        discount_id: "",
      },
      memberType: [],
      rules: {
        name: [{ required: true, message: "请输入券模板名称", trigger: "blur" }],
        discountCode: [{ required: true, validator: discountCodeFun }],
        type: [{ required: true, message: "请输入券类型", trigger: "change" }]
      },
      typeList: [],
      rqStatus: false,
      hylxList: [],
      hydjList: [],
      thresholdValue: false,
      defaultCheckedKeys: [],
      cascaderValue: [],
      selectValue: [],
      productsList: [],
      titles: ["待选商品", "已选商品"],
      titles2: ["待选品类", "已选品类"],
      titles3: ["待选类型", "已选类型"],
      titles4: ["待选分销商", "已选分销商"],
      transferValue: [],
      transferProtype: [],
      treeProtyLIST: [],
      PLProtyLIST: [],
      receiveWay: false,
      couponStatus: true,
      coupValuStatus: false,
      zdPeo: false,
      zdPeoValue: [],
      zdPeoProductList: [],
      member_level: [],
      MerchantLIST: [],
      discount_List: [],
      MerchantValue: [],
      arrMax: [],
      applicabilityDisabled: false
    };
  },
  watch: {
    "editFormFields.applicable_people"(e) {
      switch (e) {
        case "1":
          this.rqStatus = false;
          this.zdPeo = false;
          break;
        case "2":
          this.rqStatus = true;
          this.zdPeo = false;
          break;
        case "3":
          this.zdPeo = true;
          this.rqStatus = false;
          break;
      }
    },
    "editFormFields.use_threshold"(e) {
      if (e == 0) {
        this.thresholdValue = false;
      } else {
        this.thresholdValue = true;
      }
    },
    "editFormFields.receive_way"(e) {
      if (e == 0) {
        this.receiveWay = false;
      } else {
        this.receiveWay = true;
      }
    },
    "editFormFields.type"(e) {
      let n = "";
      let v = "";
      this.typeList.forEach(i => {
        if (i.value == e) {
          n = i.label;
          v = i.value
        }
      });
      if (n == "兑换券") {
        this.coupValuStatus = false;
        this.editFormFields.is_entry_accoun = "1";
        this.applicabilityDisabled = true; //兑换券只能选择商品
      } else {
        this.coupValuStatus = true;
        this.editFormFields.is_entry_accoun = "0";
        this.applicabilityDisabled = false;
        if (n == "折扣券") {
          this.couponStatus = false;
        } else {
          //代金券,优惠券
          this.couponStatus = true;
        }
      }
      let params = {
        order: "desc",
        page: 1,
        rows: 100,
        sort: "id",
        wheres: `[{\"name\":\"spare2\",\"value\":\"${e
          }\",\"displayType\":\"like\"}]`
      };
      this.http
        .post("/api/Mall_preferential_scheme/getPageDataPre", params)
        .then(res => {
          console.log(res, "v")
          if (res.rows.length > 0) {
            this.discount_List = []
            res.rows.forEach(i => {
              let obj = {
                label: i.name,
                value: i.id,
                key: i.id
              };
              this.discount_List.push(obj);
            });
            console.log(this.discount_List, "v")
          } else {
            this.discount_List = []
          }
        });


    }
  },
  created() {
    this.http.post("/api/SupplierNews/GetMebCoupon").then(res => {
      // this.$nextTick(() => {
      this.treeTransferData = res.data;
      console.log(this.treeTransferData);

      // });
    });

  },
  methods: {
    // 渲染指定商户树状
    // specifiedMerchant() {
    //   this.http.post("/api/SupplierNews/GetMebCoupon").then(res => {
    //     // this.$nextTick(() => {
    //       this.treeTransferData = JSON.parse(JSON.stringify(res.data));
    //       console.log(this.treeTransferData);

    //     // });
    //   });

    renderFunc(h, option) {
      return option.name.length > 8 ? (
        <el-tooltip effect="light" content={option.name} placement="top">
          <span>{option.name}</span>
        </el-tooltip>
      ) : (
        <span>{option.name}</span>
      );
    },
    GetVueDictionary() {
      let that = this;
      this.transferValue = [];
      this.typeList = [];
      this.hylxList = [];
      this.productsList = [];
      this.selectValue = [];
      let param = ["Coupon_Type", "Member_Type", "supplier", "preferential"];
      this.http.post("/api/Dictionary/GetVueDictionary", param).then(res => {
        res.forEach(o => {
          if (o.dicNo == "Coupon_Type") {
            o.data.forEach(i => {
              let obj = {
                label: i.value,
                value: i.key
              };
              this.typeList.push(obj);
            });
          } else if (o.dicNo == "Member_Type") {
            o.data.forEach(i => {
              let obj = {
                label: i.value,
                value: i.key,
                key: i.key
              };
              this.hylxList.push(obj);
            });
          } else if (o.dicNo == "supplier") {
            o.data.forEach(i => {
              let obj = {
                label: i.value,
                value: i.key,
                key: i.key
              };
              this.MerchantLIST.push(obj);
            });
          }
        });
      });
      this.http.get("/api/producttypes/GetProductType").then(res => {
        this.PLProtyLIST = res.data;
        function arrReduce(someArr) {
          for (let i = 0; i < someArr.length; i++) {
            if (someArr[i].children) {
              arrReduce(someArr[i].children);
              that.arrMax.push(someArr[i]);
            } else {
              that.arrMax.push(someArr[i]);
            }
          }
        }
        arrReduce(res.data);
      });
    },
    changeCasc() {
      let params = {
        typeid: this.cascaderValue[this.cascaderValue.length - 1]
      };
      this.http.post("/api/Mall_good/GetCouponGoods", params).then(res => {
        let arr = [];
        this.productsList = [];
        if (res.data.length != 0) {
          res.data.forEach(i => {
            let obj = {
              label: i.name,
              value: i.goods_id,
              key: i.goods_id,
              id: i.goods_id,
              ...i
            };
            this.productsList.push(obj);
          });
        }
      });
    },
    submit(formName) {
      // if(this.editFormFields.name==""){
      //         this.$Message.error("请输入券模板名称");
      //       return;
      //       }
      //       if(this.editFormFields.type==""){
      //         this.$Message.error("请输入券类型");
      //   return;
      //       }
      this.$refs[formName].validate(valid => {
        if (valid) {
          let param = {
            detailData: [],
            mainData: {
              coupon: {
                ...JSON.parse(JSON.stringify(this.editFormFields)),
                coupon_cover:
                  this.formFields1.coupon_cover.length == 0
                    ? ""
                    : this.formFields1.coupon_cover[0].path
              }
            }
          };
          // 指定品类
          if (this.editFormFields.applicability == 2) {
            let arr = [];
            let axc = [];
            this.transferValue.forEach(i => {
              arr.push(i[i.length - 1]);
            });
            this.arrMax.forEach(i => {
              if (arr.includes(i.id)) {
                let obj = {
                  id: i.id,
                  value: i.typeName
                };
                axc.push(obj);
              }
            });
            param.detailData = [
              {
                GoodType: axc
              }
            ];
          }
          // 指定商品
          if (this.editFormFields.applicability == 3) {
            let info = [];
            if (this.applicabilityDisabled) {
              this.productsList.forEach(j => {
                if (this.selectValue == j.goods_id) {
                  info.push(j);
                }
              });
            } else {
              this.selectValue.forEach(i => {
                this.productsList.forEach(j => {
                  if (i == j.goods_id) {
                    info.push(j);
                  }
                });
              });
            }

            param.detailData = [
              {
                GoodInfo: info
              }
            ];
          }
          // 指定商户
          if (this.editFormFields.applicability == 4) {
            this.MerchantValue = []
            //  console.log(this.$refs.insideChooseProject.dataRight,"this.$refs.insideChooseProject")
            var dataRightArr = this.$refs.insideChooseProject.dataRight
            dataRightArr.forEach((item) => {
              this.MerchantValue.push(item.id)
            })
            param.mainData.coupon.appointed_supplier =
              this.MerchantValue.join() + ",";
          }
          delete param.mainData.coupon.useTime;
          delete param.mainData.coupon.receiveTime;
          // 领取时间
          if (this.editFormFields.receiveTime) {
            param.mainData.coupon.receive_starttime = this.editFormFields.receiveTime[0];
            param.mainData.coupon.receive_endtime = this.editFormFields.receiveTime[1];
          }
          param.mainData.coupon.member_type = this.memberType.join();
          let editFormType = true
          if (this.editFormFields.type == '2' && param.detailData[0] && param.detailData[0].GoodInfo.length == 0) {
            this.$Message.error("请选择指定商品且商品不能为空");
            editFormType = false
          } else {
            editFormType = true
          }
          if (this.title == "优惠券模板--新增" && editFormType) {
            this.http.post("/api/MebCoupon/Add", param).then(res => {
              if (res.status) {
                this.model = false;
                this.$store.getters.data().viewPageTest.refresh();
                this.$Message.success("新增成功");
              }else{
                this.$Message.error(res.message);
              }
            });
          }
          // else {
          //   this.http.post("/api/MebCoupon/update", param).then(res => {
          //     if (res.status) {
          //       this.model = false;
          //       this.$store.getters.data().viewPageTest.refresh();
          //       this.$Message.success("修改成功");
          //     }
          //   });
          // }
        }
      });
    }
  }
}
</script>
<style>
.sysm>.el-form-item__content {
  width: 87% !important;
}
</style>
<style lang="scss" scoped>
.hx {
  margin: 20px 0;
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
}

.z {
  width: 50px;
}

.el-form-item {
  width: 47% !important;
}

.el-transfer {
  margin-top: 20px;
}

.treeS {
  height: 200px;
  overflow-y: scroll;
}

.cascader {
  margin-top: 20px;
  display: flex;

  .casd {
    width: 300px;
    max-height: 300px;
    overflow-y: auto;
  }

  .el-transfer {
    margin-left: 20px;
    margin-top: 0;
  }
}

.sysm {
  width: 100% !important;
  display: flex;
}

.meInt {
  width: 92%;
}

.fr {
  float: right;
}
</style>
